'use strict'

const http = require('http');
const fs = require('fs');
const {
  promisify
} = require('util');
const path = require('path');
const socketIo = require('socket.io');
const mime = require('mime');
const opn = require('opn');

const readFile = promisify(fs.readFile); //读取文件

//服务器处理函数
function handler(req, res) {
  let url = req.url; //当前路径
  let filePath = '' //记录文件路径，用于发送文件

  if (url === '/') {
    filePath = path.join(__dirname, '../client/index.html');
  } else if (url === '/favicon.ico') { //网站图标
    return;
  } else if (url === '/ctr') { //控制页
    filePath = path.join(__dirname, '../client/ctr.html');
  } else {
    filePath = path.join(__dirname, '../client' + url);
  }
  res.writeHead(200, {
    'Content-type': mime.lookup(filePath) //判断文件类型
  });

  readFile(filePath).then((data) => {
    res.end(data); //发送读取到的文件
  }).catch((err) => {
    console.log(err); //输出错误
  });
}


const app = http.createServer(handler).listen(3000);

const io = socketIo(app);

io.on('connection', (socket) => {
  socket.on('start', function (data) {
    socket.broadcast.emit('start', data);
  })
  socket.on('move', function (data) {
    socket.broadcast.emit('move', data);
  })
  socket.on('style', function (data) {
    socket.broadcast.emit('style', data);
  });
  socket.on('clear', function () {
    socket.broadcast.emit('clear');
  });
  socket.on('say', function (data) {
    socket.broadcast.emit('listen', data);
  })
});
opn('http://localhost:3000');
opn('http://localhost:3000');
console.log('用浏览器打开 localhost:3000');